import { useCheckLogin } from "../../hook/useCheckLogin.ts";
import AdminLayout from "../AdminLayout/index.tsx";
import { useLoadSysConfig } from "../../hook/useLoadSysConfig.ts";
import { Spin } from "antd";
import { useConfig } from "../../hook/D8dConfigProvider.tsx";
import AuthPage from "../../pages/AdminPages/AuthPage.tsx";
import { useEffect } from "react";

interface AdminLoaderProps {
  loaderPath?: string;
  /** 登录成功后的重定向路径 */
  redirectPath?: string;
}

const AdminLoader = ({ loaderPath = 'admin', redirectPath }: AdminLoaderProps) => {
  const { useLoad, authMode, authConfig } = useConfig();
  // 获取登录状态和登录检查的加载状态
  const { isLogin, isLoading: isCheckingLogin } = useCheckLogin();
  // 只有在登录后才启用系统配置加载
  const sysConfigLoaded = useLoadSysConfig({ enabled: !!isLogin });
  
  useEffect(() => {
    // 只在登录状态下执行额外的加载逻辑
    if (isLogin) {
      useLoad?.();
    }
  }, [isLogin, useLoad]);

  // 正在检查登录状态
  if (isCheckingLogin) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" />
      </div>
    );
  }

  // 未登录
  if (!isLogin) {
    return (
      <AuthPage 
        loaderPath={loaderPath}
        authMode={authMode}
        authConfig={authConfig}
        redirectPath={redirectPath}
      />
    );
  }

  // 已登录但系统配置还未加载完成
  if (!sysConfigLoaded) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" />
      </div>
    );
  }

  // 已登录且系统配置加载完成
  return <AdminLayout />;
};

export default AdminLoader;
